class Admins::GroupsController < Admins::BaseController

  def index
    authorize! :manage, User
    @users = User.all.order("created_at desc")
    @groups = Group.all.order("created_at desc")
    @permissions = Permission.all.group_by(&:class_name)
  end

  def create
    @group = Group.create(params[:group].permit(:name))    
    respond_to do |format|      
      if @group.valid?        
        items = params[:permission] || []
        items.each do |item|          
          @group.group_permissions.create(permission_id: item)
        end
        format.html{ render partial: "item", locals: {group: @group} }
      else
        format.json{ render :json => @group.errors.full_messages, :status => 403 }
      end
    end
  end

  def edit
    @permissions = Permission.all.group_by(&:class_name)
    @group = Group.find(params[:id])
    respond_to do |format|
      format.js
    end
  end

  def update
    @group = Group.find(params[:id])
    respond_to do |format|
      if @group.update_attributes(params[:group].permit(:name))
        @group.group_permissions.destroy_all
        items = params[:permission] || []
        items.each do |item|          
          @group.group_permissions.create(permission_id: item)
        end
        format.json{ render json: @group }
      else
        format.json{ render json: @group.errors.full_messages, status: 403 }
      end
    end
  end

  def destroy
    user =  User.find params[:id]
    user.destroy
    flash[:success] = '用户删除成功'
    redirect_to :action => :index
  end

  def permissions
    @group = Group.find(params[:id])
    permissions = @group.permissions.group_by(&:class_name)
    respond_to do |format|
      format.html{ render partial: "abilities", locals: {permissions: permissions} }
    end
  end
end